# try and detect host OS..
HOST :=
ifeq ($(OS),DOS)
    HOST := dos
else
    ifeq ($(OS),Windows_NT)
        HOST := win32
    else
        ifdef WINDIR
            HOST := win32
        else
            ifdef windir
                HOST := win32
        else
        ifdef HOME
            HOST := linux
        endif
            endif
        endif
    endif
endif

ifeq ($(HOST),DOS)
	#error
	@echo "DOS is not supported."
else
	ifeq ($(HOST),win32)
		DLL_EXT := .dll
		EXE_EXT := .exe
		MKDIR := mkdir
		CP := cp
		RM := rm -f
		IINCDIR := inc
		ifdef USEGCC
			GCC_OPT := -gen gcc -Wl "-Wall -O2"
			GCC_LINK := -Wl "-lfbgfx,-lm,-lgdi32,-lopengl32,-luser32,-lcrtdll,-lfbmt,-lkernel32"
		else
			GCC_OPT :=
			GCC_LINK :=
		endif
	else
		DLL_EXT := .so
		MKDIR := mkdir
		CP := cp
		RM := rm -f
		IINCDIR := include/freebasic
		EXE_EXT := .elf
	endif
endif

ifdef USEGCC
	FBC_OPT := -w all -mt -i inc $(GCC_OPT)
else
	FBC_OPT := -w all -mt -i inc
endif

ifdef DLL
	FBC_LINK := -p lib -dll -mt -x
	TCOMMLIB := lib/tcomm$(DLL_EXT)
	LIB := lib/libtgfx$(DLL_EXT)
	DLL_OPT := -d DLL
else
	DLL_OPT :=
	FBC_LINK := -lib -mt -x
	TCOMMLIB := lib/libtcomm.a
	LIB := lib/libtgfx.a
endif

FBC := fbc

SOURCES := $(wildcard src/tgfx/tgfx-*.bas)
OBJS := $(patsubst %.bas,%.o,$(SOURCES))

TCOMMSRC := src/tcomm/tcomm.bas
TCOMMOBJ := src/tcomm/tcomm.o

EX_SOURCES := $(wildcard examples/*.bas)
EX_EXE := $(patsubst %.bas,%$(EXE_EXT),$(EX_SOURCES))

DOC_DIRS := inc docs/index

ALL : $(LIB)

.PHONY : $(LIB)
$(LIB) : $(TCOMMLIB) $(OBJS)
	$(FBC) $(OPT) $(FBC_LINK) $(LIB) $(OBJS)

.PHONY : $(TCOMMLIB)
$(TCOMMLIB) : $(TCOMMOBJ)
	$(FBC) $(OPT) $(FBC_LINK) $(TCOMMLIB) $(TCOMMOBJ)

src/%.o : src/%.bas
	$(FBC) -c $(OPT) $(FBC_OPT) $(DLL_OPT) $< -o $@

examples/%.exe :
	$(FBC) -p lib -x $@ $(OPT) $(FBC_OPT) $(GCC_LINK) $(patsubst %$(EXE_EXT),%.bas,$@)

.PHONY : clean
clean :
	$(RM) $(OBJS) $(TCOMMOBJ)
	$(RM) lib/*
	$(RM) $(EX_EXE)

.PHONY : examples
examples : $(LIB) $(EX_EXE)

.PHONY : docs
docs :
	$(PERL) $(ND_DIR)/NaturalDocs -p docs $(addprefix -i ,$(DOC_DIRS)) -s fbext -o FramedHTML docs/html

.PHONY : install
install : $(LIB)
	$(CP) $(LIB) $(INSTALLDIR)/lib/$(HOST)
	$(CP) $(TCOMMLIB) $(INSTALLDIR)/lib/$(HOST)
	$(CP) inc/tcomm.bi $(INSTALLDIR)/$(IINCDIR)
	$(CP) inc/tgfx.bi $(INSTALLDIR)/$(IINCDIR)
	$(MKDIR) $(INSTALLDIR)/$(IINCDIR)/tgfx
	$(CP) inc/tgfx/*.bi $(INSTALLDIR)/$(IINCDIR)/tgfx
